using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Threading;

namespace SpoonStream
{
	public class StreamSniffer
	{
		private Socket _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
		private byte[] _buffer = new byte[65000];
		private EndPoint _endPoint = new IPEndPoint(IPAddress.Any, 0);
		private SocketFlags _flags;
		private IPPacketInformation _packetInfo;
		private FileStream _file;
		private BinaryWriter _bw;
		private BinaryReader _br;
		private IPEndPoint _dest = new IPEndPoint(IPAddress.Loopback, 1234);

		public StreamSniffer()
		{
			_file = new FileStream("c:/data.tmp", FileMode.OpenOrCreate, FileAccess.ReadWrite);
			_bw = new BinaryWriter(_file);
			_br = new BinaryReader(_file);

			_socket.Bind(new IPEndPoint(IPAddress.Any, 1000));
			_socket.BeginReceiveMessageFrom(_buffer, 0, _buffer.Length, SocketFlags.None, ref _endPoint,
											new AsyncCallback(Receive), null);
		}

		public void Send()
		{
			_file.Position = 0;
			DateTime startTime = DateTime.Now;
			bool set = false;
			while (_file.Position < _file.Length)
			{
				DateTime time = new DateTime(_br.ReadInt64());
				if (!set)
				{
					startTime = time;
					set = true;
				}
				int count = _br.ReadInt32();
				byte[] data = _br.ReadBytes(count);

				Console.WriteLine((time - startTime).TotalMilliseconds);

				Thread.Sleep(time - startTime);
				startTime = time;
				
				_socket.SendTo(data, _dest);
			}
		}

		private void Receive(IAsyncResult ar)
		{
			int count = _socket.EndReceiveMessageFrom(ar, ref _flags, ref _endPoint, out _packetInfo);

			_bw.Write(DateTime.Now.Ticks);
			_bw.Write(count);
			_bw.Write(_buffer, 0, count);

			Console.WriteLine(DateTime.Now.Ticks);

			_file.Flush();

			_socket.BeginReceiveMessageFrom(_buffer, 0, _buffer.Length, SocketFlags.None, ref _endPoint,
											new AsyncCallback(Receive), null);
		}
	}
}
